<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" clearable placeholder="请输入用户名" style="width: 240px" @change="handQuery" />
      </el-form-item>
      <el-form-item label="注册时间" prop="dateRange" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="attendantList">
      <el-table-column align="center" label="用户名" v-if="columns.username.visible">
        <template #default="scope">
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-avatar
              :size="40"
              :src="scope.row.avatar"
              fit="cover"
              style="flex-shrink: 0;"
            />
           <span class="user-name">{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="account" align="center" label="账号" :show-overflow-tooltip="true" v-if="columns.account.visible">
        <template #default="scope">
          <span>{{ scope.row.account || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" align="center" label="手机号" :show-overflow-tooltip="true" v-if="columns.phone.visible">
        <template #default="scope">
          <span>{{ scope.row.phone || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sex" align="center" label="性别" v-if="columns.sex.visible">
        <template #default="scope">
          <el-tag :type="scope.row.sex === -1 ? 'info' : scope.row.sex === 1 ? 'primary' : 'success'">
            {{ scope.row.sex === -1 ? '未知' : scope.row.sex === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="age" align="center" label="年龄" width="80" v-if="columns.age.visible">
        <template #default="scope">
          <span>{{ scope.row.age || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="账号状态" v-if="columns.status.visible">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="birthday" align="center" label="生日" v-if="columns.birthday.visible"></el-table-column>
      <el-table-column prop="createTime" align="center" width="160" label="注册时间" v-if="columns.createTime.visible"></el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="200" v-if="columns.action.visible">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 修改陪诊师对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form :model="form" ref="attendantRef" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar" :limit="1" />
          <div style="margin-top: 8px; color: #909399; font-size: 12px;">
            修改头像要点击确定才能保存哦
          </div>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <attendant-detail-dialog 
      :detailDialogVisible="detailDialogVisible" 
      :attendantId="selectedAttendantId"
      @handleClose="handleDetailDialogClose"
    />
  </div>
</template>

<script setup name="Attendant">
import { listAttendant, updateAttendant, deleteAttendant, getAttendantUpdateInfo } from "@/api/attendant/attendant";
import AttendantDetailDialog from "./components/AttendantDetailDialog.vue";
import { changeAttendantStatus } from "@/api/attendant/attendant";

const { proxy } = getCurrentInstance();

// 响应式数据
const showSearch = ref(true);
const dateRange = ref([]);
const attendantList = ref([]);
const loading = ref(true);
const total = ref(0);
const open = ref(false);
const title = ref("");
const detailDialogVisible = ref(false);
const selectedAttendantId = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: undefined,
    startTime: undefined,
    endTime: undefined,
  },
  rules: {
    username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
    avatar: [{ required: true, message: "头像不能为空", trigger: "blur" }],
  },
});

// 列显隐信息
const columns = ref({
  username: { label: "用户名", visible: true },
  account: { label: "账号", visible: true },
  birthday: { label: "生日", visible: true },
  sex: { label: "性别", visible: true },
  age: { label: "年龄", visible: true },
  status: { label: "账号状态", visible: true },
  phone: { label: "手机号", visible: true },
  createTime: { label: "创建时间", visible: true },
  action: { label: "操作", visible: true },
});

const { form, rules, queryParams } = toRefs(data);



const getList = () => {
  loading.value = true;
  
  // 处理日期范围查询
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 00:00:00";
  } else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  
  listAttendant(queryParams.value).then((res) => {
    loading.value = false;
    attendantList.value = res.rows;
    total.value = res.total;
  });
};

const handQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = [];
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  proxy.resetForm("queryRef");
  handQuery();
};

const handleUpdate = (row) => {
  reset();
  getAttendantUpdateInfo(row.id).then((res) => {
    form.value = {
      id: res.data.id,
      avatar: res.data.avatar,
      username: res.data.username
    };
    open.value = true;
    title.value = "修改陪诊师信息";
  });
};

const handleDelete = (row) => {
  proxy.$modal
    .confirm('是否确认删除陪诊师"' + row.username + '"？')
    .then(function () {
      return deleteAttendant(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

const handleStatusChange = (row) => {
  let text = row.status === 0 ? '启用' : '禁用';
  proxy.$modal
    .confirm('是否确认' + text + '陪诊师"' + row.username + '"？'
             + (text === '启用' ? '启用后陪诊师将可以执行接单等功能' : '禁用后陪诊师将无法执行接单等功能'))
    .then(function () {
      return changeAttendantStatus(row.id, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功');
      getList();
    })
    .catch(() => {
      row.status = row.status === 0 ? 1 : 0;
    });
};

const handleView = (row) => {
  selectedAttendantId.value = row.id;
  detailDialogVisible.value = true;
};

const submitForm = () => {
  proxy.$refs["attendantRef"].validate((valid) => {
    if (valid) {
      updateAttendant(form.value).then((res) => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      });
    }
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    id: undefined,
    avatar: undefined,
    username: undefined,
  };
  proxy.resetForm("attendantRef");
};

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false;
  selectedAttendantId.value = undefined;
};


getList();
</script>


<style scoped lang="scss">
.user-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>